<template>
  <div class="photo-category">
    <!-- 分类 -->
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu 
        :default-active="menuActive + ''" 
        :active-text-color="theme"
        @select="handleSelect"
      >
        <el-menu-item :index="index + ''" v-for="(item, index) in photoGroupList" :key="index">
          <span slot="title">{{ item.name }}</span>
        </el-menu-item>
      </el-menu>
    </el-scrollbar>
    <!-- 新建 -->
    <el-popover width="160" v-model="visibleCreate">
      <el-input 
        v-model="photoGroupName" 
        size="small" 
        maxlength="10" 
        placeholder="请输入分类名称"
      ></el-input>
      <div class="create-group-btns">
        <el-button size="mini" type="text" @click="visibleCreate = false">取消</el-button>
        <el-button type="primary" size="mini" :disabled="createDisabled" @click="handleCreate">提交</el-button>
      </div>
      <el-button slot="reference" class="create" type="text">新建分类</el-button>
    </el-popover>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { isStrEmpty } from '@/utils/validate'

export default {
  name: 'PhotoCategory',
  data() {
    return {
      menuActive: 0,
      visibleCreate: false,
      photoGroupName: '',
    }
  },
  computed: {
    ...mapGetters({
      photoGroupList: 'photoGroups'
    }),
    theme() {
      return this.$store.state.settings.theme
    },
    createDisabled() {
      return isStrEmpty(this.photoGroupName)
    }
  },
  created() {
    if (!this.photoGroupList.length) {
      this.getPhotoGroups()
    }
  },
  methods: {
    // 分类切换
    handleSelect(index) {
      const currentGroupItem = this.photoGroupList[index]
      currentGroupItem.menuIndex = Number(index)
      this.$emit('group-select', currentGroupItem)
    },
    // 新建分类
    async handleCreate() {
      const createData = await this.createPhotoGroup({ name: this.photoGroupName })
      this.visibleCreate = false
      this.photoGroupName = ''
      this.$nextTick(() => {
        const index = this.photoGroupList.findIndex(v => v.id == createData.id)
        // 选中新建的分类
        if (index !== -1) {
          this.menuActive = index
          this.handleSelect(index)
        }
      })
    },
    // 映射方法
    ...mapActions('photoGroup', {
      getPhotoGroups: 'getPhotoGroups',
      createPhotoGroup: 'createPhotoGroup',
      updatePhotoGroup: 'updatePhotoGroup'
    })
  },
}
</script>

<style lang="scss">
.el-popover {
  .create-group-btns {
    margin-top: 12px;
    text-align: right;
  }
}
.photo-category {
  .create {
    display: block;
    margin: 0 auto;
  }
  .el-scrollbar {
    height: 360px;
  }
  .scrollbar-wrapper {
    overflow-x: hidden !important;
  }
}
</style>